package edu.ycu.aladdin.collector.service;

import com.alibaba.dubbo.config.annotation.Service;
import edu.ycu.aladdin.collector.api.CrawlerConfigService;
import edu.ycu.aladdin.collector.api.entity.CrawlerConfig;
import edu.ycu.aladdin.collector.detail.RedisCrawlerConfigPool;
import edu.ycu.aladdin.collector.utils.CoverUtil;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Site;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 爬虫配置服务 Redis 实现.
 *
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @see us.codecraft.webmagic.Site
 * @since 1.0
 */
@Service(interfaceClass = CrawlerConfigService.class, timeout = 10000)
@Component
public class CrawlerConfigRedisService implements CrawlerConfigService {

    private final RedisCrawlerConfigPool agentPool;

    public CrawlerConfigRedisService(RedisCrawlerConfigPool agentPool) {
        this.agentPool = agentPool;
    }

    @Override
    public void addConfig(CrawlerConfig config) {
        agentPool.addConfig(CoverUtil.parseFromConfig(config));
    }

    @Override
    public void delConfig(CrawlerConfig config) {
        agentPool.delConfig(CoverUtil.parseFromConfig(config));
    }

    @Override
    public void delConfig(String id) {
        agentPool.delConfig(id);
    }

    @Override
    public Map<Object, Object> allWithId() {
        Map<Object, Object> pool = agentPool.getPool();
        Map<Object, Object> configMap = new HashMap<>(pool.size());
        pool.forEach((key, val) -> {
            configMap.put(key, CoverUtil.parseFromSite((Site) val));
        });
        return configMap;
    }

    @Override
    public List<CrawlerConfig> getAllConfig() {

        List<CrawlerConfig> crawlerConfigs = new ArrayList<>();

        Site[] sites = agentPool.getAll();
        if (sites != null && sites.length > 0) {
            int len = sites.length;

            for (Site site : sites) {
                crawlerConfigs.add(CoverUtil.parseFromSite(site));
            }
            return crawlerConfigs;
        }
        return crawlerConfigs;
    }
}
